(function() {

    var start = document.getElementsByClassName('start')[0];
    var stop = document.getElementsByClassName('stop')[0];
    var that = null;
    var timer = null;
    // 创建游戏的构造函数
    function Game(map) {
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
        that = this;
    }

    // 对游戏进行初始化
    Game.prototype.init = function() {
        // 对食物进行初始化
        this.food.init(this.map);

        // 对小蛇进行初始化
        this.snake.init(this.map);

        this.runSnake(this.food, this.map);
        this.bindKeyEvent();
    };

    // 创建一个让小蛇跑起来的方法
    Game.prototype.runSnake = function(food, map) {
        start.addEventListener('click', function() {
            timer = setInterval(function() {
                this.snake.move(food, map);
                this.snake.init(map);

                //计算小蛇的最大移动范围
                var maxX = map.offsetWidth / this.snake.width;
                var maxY = map.offsetHeight / this.snake.height;

                // 计算小蛇移动过程中的坐标
                var headX = this.snake.body[0].x;
                var headY = this.snake.body[0].y;

                // 判断小蛇是否撞墙
                if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
                    // 游戏结束， 弹出对话框提示最终得分
                    alert('游戏结束！您的得分为：' + this.snake.score);
                    clearInterval(timer);
                }

            }.bind(that), 150)
        }, false);
        stop.addEventListener('click', function() {
            clearInterval(timer);
        }, false)
    };

    // 创建一个改变小蛇运动方向的方法
    Game.prototype.bindKeyEvent = function() {
        document.addEventListener('keydown', function(e) {
            switch (e.keyCode) {
                case 37:
                    this.snake.direction = 'left';
                    break;
                case 38:
                    this.snake.direction = 'top';
                    break;
                case 39:
                    this.snake.direction = 'right';
                    break;
                case 40:
                    this.snake.direction = 'bottom';
                    break;
            }
        }.bind(that), false)
    };

    // 将游戏的构造函数暴露到全局
    window.Game = Game;
})();

var map = document.getElementsByClassName('map')[0];
var game = new Game(map);

game.init();